import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import layout from '@/layout'
import home from '@/views/home'
import ask from '@/views/ask'
import video from '@/views/video'
import mine from '@/views/mine'
import store from '@/store'
import edit from '@/views/mine/edit'
import details from '@/views/details'
import search from '@/views/search'
import serp from '@/views/search/serp'
import chat from '@/views/mine/chat'
import { Toast } from 'vant'
Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  { path: '/', redirect: '/layout/home' },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    path: '/chat',
    name: 'chat',
    component: chat
  },
  {
    path: '/serp',
    name: 'serp',
    component: serp
  },
  {
    path: '/details',
    name: 'details',
    component: details
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/edit',
    name: 'edit',
    component: edit
  },
  {
    path: '/layout',
    name: 'layout',
    component: layout,
    children: [
      { name: 'home', path: 'home', component: home },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },
      { name: 'mine', path: 'mine', component: mine }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.name !== 'mine') {
    next()
  } else {
    if (store.state.tokenobj.token) {
      next()
    } else {
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
      Toast.fail('请先登录')
    }
  }
})
export default router
